<link rel="stylesheet" href="http://lab.lepture.com/editor/editor.css" />
<script type="text/javascript" src="http://lab.lepture.com/editor/editor.js"></script>
<script type="text/javascript" src="http://lab.lepture.com/editor/marked.js"></script>

<header ng-if="!root.sidebarEnabled" class="main-header">
    <div class="container topnav">
        <div class="universal-topnav-container">
            <!-- Left -->   
            <a href="./"><img ng-show="!root.twitterSession" src="../images/loklak_icon_yellow_45x45_transparent.png" alt="Loklak logo"></a>
            <div class="hidden-xs universal-topnav-item list-of-views">
                <ul ng-show="root.twitterSession">
                    <li ng-repeat="navItem in root.topNavItems">
                        <a ng-class="(navItem.title == root.currentView) ? 'active-view-nav' : ''" ng-href="{{navItem.link}}"><span class="{{navItem.icon}}"></span><span class="nav-item-title">{{navItem.title}}</span></a>
                    </li>
                </ul>
            </div>
            <!-- Right -->
            <div class="universal-topnav-item topnav-user-actions">
                <img class="hidden-xs" ng-show="root.twitterSession" src="../images/loklak_icon_yellow_45x45_transparent.png" alt="Loklak logo" id="loklak-nav-logo">
                <div global-search-form class="hidden-xs"></div>  
                <div twitter-session="root.twitterSession" ng-class="{'isNotLoggedIn': !root.twitterSession, 'signin-twitter': true}" signin-twitter hello="root.hello" ></div>
                <ul class="hidden-xs global-tweet-button-container" ng-if="root.twitterSession">
                    <li>
                        <button id="global-new-tweet-button" type="button" class="js-global-new-tweet js-tooltip btn primary-btn tweet-btn js-dynamic-tooltip btn-loklak-blue" data-placement="bottom" data-component-term="new_tweet_button" data-original-title=""  data-toggle="modal" data-target="#myModal" >
                            <span class="fa fa-twitter"></span>
                            <span class="text hidden-xs hidden-sm hidden-md">Tweet</span>
                        </button>
                    </li>
                </ul>
            </div>

            <!-- Mobile nav -->
            <div class="visible-xs hidden-mobile-nav">
                <div class="left-logo-and-brand">
                    <img ng-show="root.twitterSession" src="../images/loklak_icon_yellow_45x45_transparent.png" alt="Loklak logo" id="loklak-nav-logo">
                </div>
                <div global-search-form ></div>  
                <div ng-show="root.twitterSession" class="hided">
                    <a id="pull" href="#" ng-click="root.ToggleMobileNav()">
                        <button id="main-nav-button" class="lines-button x arrow arrow-left" type="button" role="button" aria-label="Toggle Navigation">
                          <span class="lines"></span>
                        </button>
                    </a>
                </div>
                <a id="sign-in-button" href="" ng-show="!root.twitterSession">
                    <span class="link" ng-href="#signupModal" data-target="#signupModal">
                        <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#signupModal"><i class="fa fa-twitter"></i>Sign in</button>
                    </span>
                </a>
            </div>
            <!-- Hidden items -->
            <div ng-show="root.twitterSession" class="hidden-items hidden-sm hidden-md hidden-lg hidden-init">
                <div class="list-of-views">
                    <ul>
                        <li ng-repeat="navItem in root.topNavItems">
                            <a ng-class="(navItem.title == root.currentView) ? 'active-view-nav' : ''" ng-href="{{navItem.link}}"><span class="{{navItem.icon}}"></span>{{navItem.title}}</a>
                        </li>
                    </ul>
                </div>
                <div class="signin-status-container">
                    <ul class="global-tweet-button-container" ng-if="root.twitterSession">
                        <li>
                            <button id="global-new-tweet-button" type="button" class="js-global-new-tweet js-tooltip btn primary-btn tweet-btn js-dynamic-tooltip btn-loklak-blue" data-placement="bottom" data-component-term="new_tweet_button" data-original-title=""  data-toggle="modal" data-target="#myModal" >
                                <span class="fa fa-twitter"></span>
                                <span class="text">Tweet</span>
                            </button>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Modal -->
<div tweet-feature-drt></div>
<div id="myModal" class="modal" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title" style="text-align:center">Compose New Tweet</h4>
        </div>
        <form role="form" id="tweet"  ng-submit="root.postTweet()"  enctype="multipart/form-data">
        <div class="modal-body">
            <div class="modal-tweet-form-container">
              
                <textarea name="tweet" id="tweet" cols="30" rows="5" class="form-control" ng-model="root.tweet" ng-change="root.tweetLengthCalculate()"></textarea>
                <input type="hidden" name="optionChoice" ng-model="root.option" id="optionChoice">
                <input type="hidden" name="mapZoomLevel" ng-model="root.mapZoomLevel" id="mapZoomLevel">
                <input type="hidden" name="latitude"  ng-model="root.latitude" id="mapLat">
                <input type="hidden" name="longitude" ng-model="root.longitude" id="mapLng">
                <input type="hidden" name="maplongWest" ng-model="root.maplongWest" id="maplongWest">
                <input type="hidden" name="maplatSouth" ng-model="root.maplatSouth" id="maplatSouth">
                <input type="hidden" name="maplongEast" ng-model="root.maplongEast" id="maplongEast">
                <input type="hidden" name="maplatNorth" ng-model="root.maplatNorth" id="maplatNorth">
                <div id="tweet-map" style="width: 100%; height: 300px;"></div>
                <textarea name="largeTextAttachment" id="largeTextAttachment" ng-model="root.largeTextAttachment"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <output id="list"></output>
            <span ng-show="root.tweetLength < 0" style="color:red;">{{root.tweetLength}}</span>
            <span ng-show="root.tweetLength < 7 && root.tweetLength >= 0" style="color:crimson;">{{root.tweetLength}}</span>
            <span ng-show="root.tweetLength >= 7 && root.tweetLength <= 140" style="color:green;">{{root.tweetLength}}</span>
            <span  class="btn btn-default btn-file fa pull-left" id="filePicker">
                <input type="file" id="fileInput" name="imageUpload" ng-model="root.imageUpload">&nbsp;&#xf030; Add Photo
            </span>
            <input type="button" class="fa fa btn btn-default pull-left" ng-if="!root.locationName" ng-click="root.getLocation()" value="&#xf041; Get Location">
            <span class="pull-left">
            <div class="dropdown" ng-if="root.locationName">
              <button class="fa btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
              {{root.locationName}}
              <span class="caret"></span>
              </button>
              <ul class="fa dropdown-menu" aria-labelledby="dropdownMenu1" id="subDropDownMenu">
                <li ng-repeat="loc in root.VariableLocations | limitTo:5"><a href="#" ng-click="root.setNewLocation($index)" class="fa" id="locationAng" onclick="changeLocationName(event)" value="{{loc}}">{{loc}}</a></li>
                <li><a href="" ng-bind="root.newLocationSet" ng-click="root.setNewLocationOther()">&#xf041; </a></li>
                <li role="separator" class="divider"></li>
                <input type="text" class="form-content" ng-model="root.newLocationSet" id="newLoc" onkeyup="return inputNewLocation(event)" >
                <li><a ng-click="root.clearLocation()">Disable Location</a></li>
              </ul>

            </div>
            </span>
            &nbsp;
            <!-- Map Tile -->
            <input type="button" class="fa fa btn btn-default pull-left" onclick="setMapTile()" id="attachMap" value="&#xf041; Attach Map">
            <input type="button" class="fa fa btn btn-default pull-left" onclick="cancelMapTile()" id="CancelMap" value="&#xf041; Cancel Map">
            <!-- End Map Tile -->
            <!-- Markdown Attachment -->
            <input type="button" class="fa fa btn btn-default pull-left" onclick="showLargeAttachment()" id="attachLargeText" value="&#xf041; Attach Text">
            <input type="button" class="fa fa btn btn-default pull-left" onclick="cancelLargeAttachment()" id="cancelLargeTextAttachment" value="&#xf041; Cancel Text">
            <!-- End Markdown -->
            <input type="submit" class="fa fa-twitter btn btn-default " value="&#xf099; Tweet">
        </div>
        </form>
    </div>

  </div>
</div>
<!-- Signup modal -->
<div id="signupModal" class="modal" role="dialog" ng-if="!root.twitterSession">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title" style="text-align:center">Signup for loklak</h4>
      </div>
      <div class="modal-body">
        <img id="loklak-signup-icon" src="../images/loklak_icon_yellow_signup.png">
        <h3 style="text-align:center;">Not on loklak? Get more out of your twitter and weibo! Use maps, create walls, see trends and reports and help to build an open education project.</h3>
      </div>
      <div class="modal-footer" style="text-align:center;">
        <button class="btn btn-info btn-flat" value="Sign up Via Twitter" ng-click="root.hello('twitter').login()"><i class="fa fa-twitter"></i>&nbsp;Signup with Twitter</button>
      </div>
    </div>

  </div>
</div>
<script>

var latitude;
var longitude;

$(document).click(function(){
 $("#subDropDownMenu").hide('slow');
 $("#subDropDownMenu").find('input').click(function(e){
    e.stopPropagation(); 
  });
 reActivate();
});

$("#subDropDownMenu").find('input').click(function(e){
  e.stopPropagation(); 
});

$('#myModal').on('shown.bs.modal', function (e) {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } 
})

  function reActivate() {
    $("#dropdownMenu1").click(function(e){
      $("#subDropDownMenu").show('slow');
    });
  }

  function removeImage() {
    $('.thumb').hide();
    $('.close').hide();
  }

  var imageHandlerCount = 1;
  var tweetmap;

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          if (imageHandlerCount!=1) {
            $('.thumb').hide();
            $('.close').hide();
            imageHandlerCount=1;
          }
          var thumbID = 'thumb'+imageHandlerCount;
          if(imageHandlerCount==1) {
            imageHandlerCount++;
            span.innerHTML = ['<img id="',thumbID, '" class="thumb" src="', e.target.result,
                              '" title="', escape(theFile.name), '"/><a id="close" class="close" href="#" onclick="removeImage();">X</a>'].join('');
            document.getElementById('list').insertBefore(span, null);
          }
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  var tempArray = [];

  function showPosition(position) {
    latitude = position.coords.latitude;
    longitude = position.coords.longitude;
    tempArray.push(latitude);
    tempArray.push(longitude);
    sendPositionDetails(latitude, longitude);
  }

  $("#tweet-map").hide();
  $("#CancelMap").hide();
  $("#largeTextAttachment").hide();
  $("#cancelLargeTextAttachment").hide();
  $('#newLocation').hide();
  $('#addNewLocation').hide();

  var popup = L.popup();
  var new_event_marker;
  L.Icon.Default.imagePath = '/images/';

  function onMapClick(e) {
    console.log(e);
    var mapZoomLevel = tweetmap.getZoom();
    $("#mapZoomLevel").val(mapZoomLevel);
    console.log(tweetmap.getBounds());
    var bound = tweetmap.getBounds();
    var longWest = parseFloat(bound._southWest.lng);
    var latSouth = parseFloat(bound._southWest.lat);
    var longEast = parseFloat(bound._northEast.lng);
    var latNorth = parseFloat(bound._northEast.lat);
    $("#maplongWest").val(longWest);
    $("#maplatSouth").val(latSouth);
    $("#maplongEast").val(longEast);
    $("#maplatNorth").val(latNorth);
    if(typeof(new_event_marker)==='undefined')
    {
      new_event_marker = new L.marker(e.latlng,{bounceOnAdd: true}).addTo(tweetmap); 
      tweetmap.panTo(new L.LatLng(e.latlng.lat, e.latlng.lng));
      latitude = e.latlng.lat;
      longitude = e.latlng.lng;
      sendPositionDetails(latitude, longitude);
    }
    else 
    {
      new_event_marker.setLatLng(e.latlng);  
      tweetmap.panTo(new L.LatLng(e.latlng.lat, e.latlng.lng));
      latitude = e.latlng.lat;
      longitude = e.latlng.lng;
      sendPositionDetails(latitude, longitude);
    }
  }

  console.log(latitude + ',' + longitude);

  function setMap(latitude, longitude) {
    tweetmap.panTo(new L.LatLng(latitude, longitude));
  }

  var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
    osmAttrib = 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
        '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
        'Imagery © <a href="http://mapbox.com">Mapbox</a>',
    osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib});

  tweetmap = L.map('tweet-map').setView([51.505, -0.159], 15).addLayer(osm);

  tweetmap.on('tileerror', function(error, tile) {
    console.log(error);
    console.log(tile);
  });

  function setMapTile() {
    $("#tweet-map").show();
    $("#CancelMap").show();
    $("#attachMap").hide();
    $('#filePicker').hide();
    $("#optionChoice").val('mapAttachment');
    setTimeout(function() {
      console.log("Triggered");
      tweetmap.invalidateSize();
    }, 1000);
  }

  function cancelMapTile() {
    $("#CancelMap").hide();
    $("#tweet-map").hide();
    $("#attachMap").show();
    $('#filePicker').show();
    $("#optionChoice").val('');
  }

  function sendPositionDetails (lat, lng) {

    console.log("Called");
    console.log(lat+','+lng);
    $("#mapLat").val(lat);
    $("#mapLng").val(lng);
    setMap(lat, lng);
  }

  function showLargeAttachment() {
    var editor = new Editor({
      element: document.getElementById('largeTextAttachment')
    });
    editor.render();

    $("#cancelLargeTextAttachment").show();
    $("#attachLargeText").hide();
    $('#filePicker').hide();
    $("#optionChoice").val('markdownAttachment');
  }

  function cancelLargeAttachment() {
    $("#attachLargeText").show();
    $('#filePicker').show();
    $(".CodeMirror.cm-s-paper").hide();
    $(".editor-toolbar").hide();
    $(".editor-statusbar").hide();
    $("#largeTextAttachment").hide();
    $("#cancelLargeTextAttachment").hide();
    $("#optionChoice").val('');
  }

  function inputNewLocation() {
    var inputBox = document.getElementById('newLoc');
    if(inputBox.value != '') {
      var x = inputBox.value;
      $('#dropdownMenu1').text(x).html();
    }
  }

  function changeLocationName(locName) {
    var x = locName.target.childNodes[0].nodeValue;
    console.log(x);
    $('#dropdownMenu1').text(x).html();
  }

  function inputNewLocation(e) {
    var inputBox = document.getElementById('newLoc');
    if(inputBox.value != '') {
      var x = inputBox.value;
      $('#dropdownMenu1').text(x).html();
    }
  }

  document.getElementById('locationAng').onclick = function (event) {
    console.log(event.target);
  }

  tweetmap.on('click', onMapClick);

document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);

</script>
